package com.kma.summer2012.server;

import com.kma.summer2012.dao.CrumbsRequestDAO;
import com.kma.summer2012.factory.DAOFactory;
import com.kma.summer2012.factory.SpringBeansFactory;
import com.kma.summer2012.model.CrumbsClient;
import com.kma.summer2012.model.CrumbsDateAndTime;
import com.kma.summer2012.model.CrumbsRequest;
import com.kma.summer2012.model.CrumbsRequestAndWork;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: EUGENE
 * Date: 3/17/13
 * Time: 4:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class CrumbsExport extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
            CrumbsRequestDAO dao = (CrumbsRequestDAO) factory.getCrumbsRequestDAO();

            ArrayList<CrumbsRequest> requestList = new ArrayList<CrumbsRequest>();
            String[] elements;
            elements = request.getParameterValues("requestId");
            CrumbsRequest crumbsRequest;
            for (String el : elements) {
                crumbsRequest = dao.getById(Integer.parseInt(el));
                requestList.add(crumbsRequest);
            }

            ArrayList<Object[]> exportData = new ArrayList<Object[]>();
            for (CrumbsRequest value:requestList){
                this.addRequestToMap(value,exportData);
            }

            HSSFWorkbook workbook = this.getExcelFile(exportData);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            int length = baos.size();

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=sampleName.xls");
            response.setContentLength(length);

            OutputStream out = response.getOutputStream();
            out.write(baos.toByteArray());

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            OutputStream out = response.getOutputStream();
            out.close();
        }

    }

    protected HSSFWorkbook getExcelFile(ArrayList<Object[]> data){
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Export sheet");

        int rownum = 0;
        for (Object [] objArr : data) {
            Row row = sheet.createRow(rownum++);
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                if(obj instanceof Date)
                    cell.setCellValue((Date)obj);
                else if(obj instanceof Boolean)
                    cell.setCellValue((Boolean)obj);
                else if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Double)
                    cell.setCellValue((Double)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
                else if(obj instanceof Short)
                    cell.setCellValue((Short)obj);
            }
        }
        return workbook;
    }

    protected ArrayList<Object[]> addRequestToMap(CrumbsRequest request, ArrayList<Object[]> data){
        if (data == null) return null;
        data.add(new Object[] {"Request export"});
        data.add(new Object[] {"Id",request.getId()});

        String DATE_FORMAT = "dd/MM/yyyy HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        data.add(new Object[] {"Date of creation",sdf.format(request.getDateOfCreation())});

        data.add(new Object[] {"State",request.getCrumbsRequestsState().getState()});

        data.add(new Object[] {"Request info",request.getRequestInfo()});

        data.add(new Object[] {"Type of work:"});
        Set<CrumbsRequestAndWork> requestAndWorks= request.getCrumbsRequestAndWorks();
        for (CrumbsRequestAndWork work:requestAndWorks){
            String workName = work.getCrumbsCatalogOfWork().getWorkname();
            Short workAmount = work.getAmountOfWork();
            data.add(new Object[] {"",workName});
            data.add(new Object[] {"",workAmount});
        }

        CrumbsClient client = request.getCrumbsClient();
        String clientInfo = this.collectClientInfo(client);
        data.add(new Object[] {"Client`s Info",clientInfo});

        data.add(new Object[] {"Requested time"});
        Set<CrumbsDateAndTime> dates = request.getCrumbsDateAndTimes();
        for (CrumbsDateAndTime dateAndTime:dates){
            Date dateBegin = dateAndTime.getDateBegin();
            Date dateEnd = dateAndTime.getDateEnd();
            String dateBeginStr = sdf.format(dateBegin);
            String dateEndStr = sdf.format(dateEnd);
            data.add(new Object[] {"",dateBeginStr,dateEndStr});
        }

        data.add(new Object[] {"Assigned time"});
        dates = request.getCrumbsDateAndTimes();
        for (CrumbsDateAndTime dateAndTime:dates){
            Date dateBegin = dateAndTime.getAssignedTimeBegin();
            Date dateEnd = dateAndTime.getAssignedTimeEnd();
            String dateBeginStr = sdf.format(dateBegin);
            String dateEndStr = sdf.format(dateEnd);
            data.add(new Object[] {"",dateBeginStr,dateEndStr});
        }
        data.add(new Object[] {"",""});

        return  data;
    }

    private String collectClientInfo(CrumbsClient client){
        String result = "";
        result += client.getName() + "\n ";
        result += client.getAdress() + "\n ";
        result += client.getMail() + "\n ";
        return result;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

}
